package com.uduemc.jcms.backend.component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.generate.entity.JcmsBackendUser;
import com.uduemc.jcms.generate.service.IJcmsBackendUserService;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

@Component
public class BackendLoginForm {

	@Autowired
	HttpServletRequest request;

	@Autowired
	ApplicationContext applicationContext;

	public void login(JcmsBackendUser jcmsBackendUser) {
		if (jcmsBackendUser == null) {
			return;
		}
		HttpSession session = request.getSession();
		session.setAttribute(BackendModule.BackendUserIdSession, String.valueOf(jcmsBackendUser.getId()));
		session.setAttribute(BackendModule.BackendUserSession, jcmsBackendUser);
	}

	public void logout() {
		HttpSession session = request.getSession();
		session.removeAttribute(BackendModule.BackendUserIdSession);
		session.removeAttribute(BackendModule.BackendUserSession);
	}

	public JcmsBackendUser getUser() {
		JcmsBackendUser backendUser = (JcmsBackendUser) request.getSession().getAttribute(BackendModule.BackendUserSession);
		if (backendUser != null) {
			return backendUser;
		}

		String backenUserId = (String) request.getSession().getAttribute(BackendModule.BackendUserIdSession);

		if (StrUtil.isNotBlank(backenUserId) && NumberUtil.isNumber(backenUserId)) {
			Long bUserId = Long.valueOf(backenUserId);
			if (bUserId != null && bUserId.longValue() > 0) {
				IJcmsBackendUserService jcmsBackendUserServiceImpl = (IJcmsBackendUserService) applicationContext.getBean("jcmsBackendUserServiceImpl");
				backendUser = jcmsBackendUserServiceImpl.getById(bUserId);
				return backendUser;
			}
		}

		throw new RuntimeException("找不到登录后台的用户！");
	}
}
